/*******************************************************************************
 * ShopSettingAction.java
 *
 * Created by Ankur
 * Last modified Date: Sep 5, 2008 11:39:37 AM by Ankur
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ******************************************************************************/

package com.printeverywhere.action;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ValidationAware;
import com.printeverywhere.delegator.ShopSettingDelegator;
import com.printeverywhere.delegator.TemplateSettingDelegator;
import com.printeverywhere.dto.ShopSettings;
import com.printeverywhere.dto.Template;
import com.printeverywhere.util.SessionUtil;

/**
 * The Class ShopSettingAction.
 */
public class ShopSettingAction extends FrontBaseSupport implements ServletRequestAware,ValidationAware {
	
	public ShopSettingAction() {
		super(true, false);
	}

	/** Logger for this class. */
	private static final Logger logger = Logger.getLogger(ShopSettingAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The shop settings. */
	private ShopSettings shopSettings;
	
	/** The file. */
	private File file;
	
	/** The templateid. */
	private int templateid;
	
	/** The checked int. */
	private int checkedInt;
	
	/** The content type. */
	private String contentType;
    
    /** The filename. */
    private String filename;
    
    /** The request. */
    private HttpServletRequest request;

	/** The template list. */
	private static List<Template> templateList;

	private String save;
	/**
	 * @return the save
	 */
	public String getSave() {
		return save;
	}

	/**
	 * @param save the save to set
	 */
	public void setSave(String save) {
		this.save = save;
	}

	/**
	 * Gets the template list from db.
	 * 
	 * @return the template list from db
	 * 
	 * @throws Exception the exception
	 */
	public String getTemplateListFromDB() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getTemplateListFromDB() - start"); //$NON-NLS-1$
		}
		shopSettings = ShopSettingDelegator.getShopSettings(SessionUtil.getUser(request).getId());
		if(shopSettings!=null && shopSettings.getTemplate()!=null)
		checkedInt = shopSettings.getTemplate().getTemplateId();
		templateList = TemplateSettingDelegator.getTemplateList();
		if (templateList.size() > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("getTemplateListFromDB() - end"); //$NON-NLS-1$
			}
			return SUCCESS;
		} else {
			
			addActionError(getText("system.no.template"));

			if (logger.isDebugEnabled()) {
				logger.debug("getTemplateListFromDB() - end"); //$NON-NLS-1$
			}
			return ERROR;
		}
	}

	/**
	 * Gets the template list.
	 * 
	 * @return the template list
	 */
	public List<Template> getTemplateList() {
		return templateList;
	}

	/**
	 * Sets the template list.
	 * 
	 * @param templateList the new template list
	 */
	public void setTemplateList(List<Template> templateList) {
		ShopSettingAction.templateList = templateList;
	}

	/**
	 * Gets the checked int.
	 * 
	 * @return the checked int
	 */
	public int getCheckedInt() {
		return checkedInt;
	}

	/**
	 * Sets the checked int.
	 * 
	 * @param checkedInt the new checked int
	 */
	public void setCheckedInt(int checkedInt) {
		this.checkedInt = checkedInt;
	}
	
	/**
	 * Save.
	 * 
	 * @return the string
	 * 
	 * @throws Exception the exception
	 */
	public String save() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("save() - start"); //$NON-NLS-1$
		}
		
		
		MultiPartRequestWrapper multiWrapper =(MultiPartRequestWrapper) ServletActionContext.getRequest();
		if (multiWrapper.hasErrors()) {
			  Collection errors = multiWrapper.getErrors();
			  Iterator i = errors.iterator();
			  while (i.hasNext()) {
			    addActionError((String) i.next());
			  }
			  return ERROR;
			}
		
		if(this.shopSettings.getTitle().length()>100){
			//FIXME Its as per Listing options Criteria
			addActionError(getText("shopsetting.error.title.length"));
			shopSettings = ShopSettingDelegator.getShopSettings(SessionUtil.getUser(request).getId());
			return INPUT;
		}
		if(this.shopSettings.getDescription().length()>50000){
			//FIXME Replace 50000 with size specified in DB.
			addActionError(getText("shopsetting.error.description.length"));
			shopSettings = ShopSettingDelegator.getShopSettings(SessionUtil.getUser(request).getId());
			return INPUT;
		}
		ShopSettings shopSettings = ShopSettingDelegator.getShopSettings(SessionUtil.getUser(request).getId());
		if(shopSettings==null){
			shopSettings=new ShopSettings();
		}
		if(file!=null){
			this.shopSettings.setLogo(FileUtils.readFileToByteArray(file));
		}else{
			this.shopSettings.setLogo(shopSettings.getLogo());	
		}
		
		if(shopSettings.getUser()!=null){
			this.shopSettings.setUser(shopSettings.getUser());
		}else{
			this.shopSettings.setUser(SessionUtil.getUser(request));
		}
		if(shopSettings.getTemplate()!=null){
			this.shopSettings.setTemplate(shopSettings.getTemplate());
		}else{
			//FIXME Replace 1 with default template id.
			List<Template> templates =TemplateSettingDelegator.getTemplateList();
			if(templates!=null && templates.size()>0)
			this.shopSettings.setTemplate(templates.get(0));
		}
		this.shopSettings.setShopId(shopSettings.getShopId());
		try{
		ShopSettingDelegator.saveShopSettings(this.shopSettings);
		}catch (Exception e) {
			addActionError(getText("saving.shopsetting.error"));
			logger.error(e);
			return INPUT;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("save() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Show shop.
	 * 
	 * @return the string
	 * 
	 * @throws Exception the exception
	 */
	public String showShop() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showShop() - start"); //$NON-NLS-1$
		}
		
		shopSettings = ShopSettingDelegator.getShopSettings(SessionUtil.getUser(request).getId());
		if(shopSettings ==null){
			shopSettings = new ShopSettings();
			List<Template> templates =TemplateSettingDelegator.getTemplateList();
			if(templates!=null && templates.size()>0)
			shopSettings.setTemplate(templates.get(0));
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showShop() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Sets the template.
	 * 
	 * @return the string
	 * 
	 * @throws Exception the exception
	 */
	public String setTemplate() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("setTemplate() - start"); //$NON-NLS-1$
		}
		ShopSettings shopSettingstemp = ShopSettingDelegator.getShopSettings(SessionUtil.getUser(request).getId());
		if(shopSettingstemp!=null && shopSettingstemp.getLogo()!=null)
		shopSettings.setLogo(shopSettingstemp.getLogo());
		shopSettings.setUser(SessionUtil.getUser(request));
		try{
			ShopSettingDelegator.saveShopSettings(shopSettings);
		}catch (Exception e) {
			addActionMessage("change.template.error");
			return INPUT;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("setTemplate() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}


	/**
	 * Gets the shop settings.
	 * 
	 * @return the shop settings
	 */
	public ShopSettings getShopSettings() {
		return shopSettings;
	}

	/**
	 * Sets the upload.
	 * 
	 * @param file the new upload
	 */
	public void setUpload(File file) {
        this.file = file;
     }
	
	/**
	 * Sets the shop settings.
	 * 
	 * @param shopSettings the new shop settings
	 */
	public void setShopSettings(ShopSettings shopSettings) {
		this.shopSettings = shopSettings;
	}

	/**
	 * Gets the templateid.
	 * 
	 * @return the templateid
	 */
	public int getTemplateid() {
		return templateid;
	}

	/**
	 * Sets the templateid.
	 * 
	 * @param templateid the new templateid
	 */
	public void setTemplateid(int templateid) {
		this.templateid = templateid;
	}

	/**
	 * Gets the file.
	 * 
	 * @return the file
	 */
	public File getFile() {
		return file;
	}

	/**
	 * Sets the file.
	 * 
	 * @param file the new file
	 */
	public void setFile(File file) {
		this.file = file;
	}
	
	/**
	 * Sets the upload content type.
	 * 
	 * @param contentType the new upload content type
	 */
	public void setUploadContentType(String contentType) {
        this.contentType = contentType;
     }
	
	/**
	 * Sets the upload file name.
	 * 
	 * @param filename the new upload file name
	 */
	public void setUploadFileName(String filename) {
        this.filename = filename;
     }

	/* (non-Javadoc)
	 * @see org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
		
	}

	/**
	 * Gets the request.
	 * 
	 * @return the request
	 */
	public HttpServletRequest getRequest() {
		return request;
	}

	/**
	 * Sets the request.
	 * 
	 * @param request the new request
	 */
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
}